<template>
  <div class="product-scope">
    <div
      class="page-header image"
      :style="bannerImage ? { backgroundImage: `url(${bannerImage})` } : {}"
    >
      <div class="header-overlay">
        <div class="container">
          <h1 class="page-title">{{ "展品范围" }}</h1>
          <p class="page-subtitle">
            {{ pageData.subtitle || "涵盖机器人全产业链的产品和技术展示" }}
          </p>
        </div>
      </div>
    </div>
    <!-- 导航菜单 -->
    <div class="nav-menu">
      <div class="container">
        <nav class="about-nav">
          <a
            @click="setActiveTab('exhibition-intro')"
            :class="['nav-item', { active: activeTab === 'exhibition-intro' }]"
          >
            展会介绍
          </a>
          <a
            @click="setActiveTab('product-scope')"
            :class="['nav-item', { active: activeTab === 'product-scope' }]"
          >
            展品范围
          </a>
          <a
            @click="setActiveTab('exhibition-highlights')"
            :class="[
              'nav-item',
              { active: activeTab === 'exhibition-highlights' },
            ]"
          >
            展会集锦
          </a>
          <a
            @click="setActiveTab('venue-intro')"
            :class="['nav-item', { active: activeTab === 'venue-intro' }]"
          >
            展馆介绍
          </a>
          <a
            @click="setActiveTab('organizer-intro')"
            :class="['nav-item', { active: activeTab === 'organizer-intro' }]"
          >
            主办方介绍
          </a>
          <a
            @click="setActiveTab('organization-structure')"
            :class="[
              'nav-item',
              { active: activeTab === 'organization-structure' },
            ]"
          >
            组织架构
          </a>
          <a
            @click="setActiveTab('past-exhibitions')"
            :class="['nav-item', { active: activeTab === 'past-exhibitions' }]"
          >
            往届展会
          </a>
          <a
            @click="setActiveTab('downloads')"
            :class="['nav-item', { active: activeTab === 'downloads' }]"
          >
            下载中心
          </a>
        </nav>
      </div>
    </div>

    <div class="container">
      <section class="scope-section">
        <div v-if="pageData.imageUrl" class="cover-wrapper">
          <img :src="pageData.imageUrl" alt="展品范围" class="cover-image" />
        </div>
        <div class="product-scope1" v-if="productScope.length">
          <div
            class="scope-card"
            v-for="(scope, idx) in productScope"
            :key="scope.id || idx"
          >
            <div class="scope-card-content">
              <div
                v-if="scope.description"
                v-html="scope.description"
                class="scope-description"
              ></div>
            </div>
          </div>
        </div>
        <div v-else class="plain-content" v-html="plainHtml"></div>
      </section>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import { Setting, Tools, Grid } from "@element-plus/icons-vue";
import { subpageApi } from "@/api/user";

export default {
  name: "ProductScope",
  setup() {
    const activeTab = ref("product-scope");
    const pageData = ref({});
    const bannerImage = ref("");
    const productScope = ref([]);
    const plainHtml = ref("");

    // 默认展品范围数据 - 仅作为API失败时的fallback
    const defaultProductScope = [];

    // 获取图标组件
    const getIconComponent = (iconName) => {
      const iconMap = {
        Setting: Setting,
        Tools: Tools,
        Grid: Grid,
      };
      return iconMap[iconName] || Setting;
    };

    // 将换行转换为 <br> 以便富文本正常显示
    const nl2br = (text) => (text || "").replace(/\r?\n/g, "<br>");

    // 加载页面数据
    const loadPageData = async () => {
      try {
        const response = await subpageApi.getSubpageByKey(
          "about",
          "product-scope"
        );
        if (response && response.code === "200" && response.data) {
          const data = response.data;
          pageData.value = {
            title: data.title || "展品范围",
            subtitle: data.subtitle || "涵盖机器人全产业链的产品和技术展示",
            imageUrl: data.imageUrl || "",
          };

          const contentStr = data && data.content ? String(data.content) : "";
          let parsedOk = false;

          if (contentStr) {
            // 优先解析为 JSON
            try {
              const parsed = JSON.parse(contentStr);
              if (Array.isArray(parsed)) {
                productScope.value = parsed.map((it, i) => ({
                  id: it.id || i + 1,
                  title: it.title && it.title !== "展品范围" ? it.title : "",
                  description: it.description
                    ? it.description
                    : nl2br(it.content || ""),
                  icon: it.icon || "Setting",
                  image: it.image || it.imageUrl || "",
                }));
                parsedOk = true;
              } else if (parsed && typeof parsed === "object") {
                // 支持对象结构：items/sections 数组 或 content 文本
                const arr = parsed.items || parsed.sections;
                if (Array.isArray(arr)) {
                  productScope.value = arr.map((it, i) => ({
                    id: it.id || i + 1,
                    title: it.title && it.title !== "展品范围" ? it.title : "",
                    description: it.description
                      ? it.description
                      : nl2br(it.content || ""),
                    icon: it.icon || "Setting",
                    image: it.image || it.imageUrl || "",
                  }));
                  parsedOk = true;
                } else if (parsed.content) {
                  productScope.value = [
                    {
                      id: 1,
                      title:
                        data.title && data.title !== "展品范围"
                          ? data.title
                          : "",
                      description: parsed.content,
                      icon: "Setting",
                      image: parsed.image || parsed.imageUrl || "",
                    },
                  ];
                  parsedOk = true;
                }
              }
            } catch (_) {
              // 非 JSON 文本处理
            }

            if (!parsedOk) {
              const text = contentStr.replace(/\r/g, "");
              // 尝试按编号拆分
              const sectionRegex = /^(\d+)\s*[\.、，]?\s*(.+)$/;
              const lines = text.split("\n").map((s) => s.trim());
              const sections = [];
              let current = null;
              for (const line of lines) {
                if (!line) continue;
                const m = line.match(sectionRegex);
                if (m) {
                  if (current) sections.push(current);
                  current = { id: Number(m[1]), title: m[2], description: "" };
                } else {
                  if (!current)
                    current = {
                      id: sections.length + 1,
                      title: `展品类别 ${sections.length + 1}`,
                      description: "",
                    };
                  current.description +=
                    (current.description ? "\n" : "") + line;
                }
              }
              if (current) sections.push(current);

              if (sections.length) {
                productScope.value = sections.map((sec, i) => ({
                  id: sec.id || i + 1,
                  title: sec.title && sec.title !== "展品范围" ? sec.title : "",
                  description: nl2br(sec.description || ""),
                  icon: "Setting",
                  image: "",
                }));
                plainHtml.value = "";
              } else {
                // 回退：逐行“标题：内容”
                const lineItems = text
                  .split("\n")
                  .map((s) => s.trim())
                  .filter(Boolean);
                if (lineItems.length) {
                  productScope.value = lineItems.map((line, i) => ({
                    id: i + 1,
                    title: line.includes("：") ? line.split("：")[0] : "",
                    description: nl2br(
                      line.includes("：")
                        ? line.slice(line.indexOf("：") + 1)
                        : line
                    ),
                    icon: "Setting",
                    image: "",
                  }));
                  plainHtml.value = "";
                } else {
                  // 最终回退：把整段作为富文本
                  productScope.value = [
                    {
                      id: 1,
                      title: "",
                      description: nl2br(text),
                      icon: "Setting",
                      image: "",
                    },
                  ];
                }
              }
            }
          } else {
            productScope.value = defaultProductScope;
          }
        } else {
          productScope.value = defaultProductScope;
        }
      } catch (error) {
        console.error("加载展品范围数据失败:", error);
        productScope.value = defaultProductScope;
      }
    };

    const loadBanner = async () => {
      try {
        const resp = await subpageApi.getContentByType("carousel_about");
        if (
          resp &&
          resp.code === "200" &&
          Array.isArray(resp.data) &&
          resp.data.length
        ) {
          const first =
            resp.data.find((it) => it.status === "active") || resp.data[0];
          const content =
            typeof first.content === "string"
              ? JSON.parse(first.content || "{}")
              : first.content || {};
          bannerImage.value = first.imageUrl || content.image || "";
        }
      } catch (e) {
        bannerImage.value = "";
      }
    };

    const setActiveTab = (tabKey) => {
      if (!tabKey) return;
      activeTab.value = tabKey;
      // 跳转到对应的子页面
      if (tabKey !== "product-scope") {
        window.location.href = `/${tabKey}`;
      }
    };

    onMounted(() => {
      loadPageData();
      loadBanner();
    });

    return {
      activeTab,
      pageData,
      bannerImage,
      productScope,
      getIconComponent,
      plainHtml,
      setActiveTab,
    };
  },
};
</script>

<style scoped>
.product-scope {
  min-height: 100vh;
  background: #f8f9fa;
  /* padding-top: 70px; */
}

.page-header {
  background: linear-gradient(135deg, #320063 0%, #4a0a8a 100%);
  color: white;
  padding: 80px 0;
  text-align: center;
}

.page-header.image {
  position: relative;
  background: none;
  padding: 0;
  height: 400px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  /* 让背景区域左右贴边，突破容器内边距 */
  width: 100vw;
  margin-left: calc(50% - 50vw);
}
.header-overlay {
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.35);
  display: flex;
  align-items: center;
}

.page-title {
  font-size: 48px;
  margin-bottom: 20px;
}

.page-subtitle {
  font-size: 18px;
  opacity: 0.9;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.scope-section {
  background: white;
  border-radius: 20px;
  padding: 3rem;
  margin: 2rem 0;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 2rem;
  color: #333;
  margin-bottom: 2rem;
  text-align: center;
}

.cover-wrapper {
  width: 100%;
  padding-bottom: 56.25%; /* 16:9 比例 */
  margin-bottom: 1.5rem;
  position: relative;
}

.cover-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 12px;
  object-fit: cover;
}

.product-scope {
  display: flex;
  flex-direction: column;
  gap: 24px;
  /* max-width: 1200px; */
  /* margin: 0 auto; */
}

.plain-content {
  white-space: pre-wrap;
  color: #444;
  line-height: 1.8;
}

.scope-card {
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  overflow: hidden;
}

.scope-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.scope-card-content {
  padding: 24px;
}

.scope-description {
  color: #555;
  line-height: 1.8;
  font-size: 1rem;
  white-space: pre-line;
  word-wrap: break-word;
  overflow-wrap: break-word;
  text-align: left;
}

.scope-description p {
  margin-bottom: 12px;
}

.scope-description ul,
.scope-description ol {
  margin: 12px 0;
  padding-left: 20px;
}

.scope-description li {
  margin-bottom: 6px;
}

.scope-description h1,
.scope-description h2,
.scope-description h3,
.scope-description h4,
.scope-description h5,
.scope-description h6 {
  margin: 16px 0 8px 0;
  color: #333;
  font-weight: 600;
}

.scope-description img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 8px 0;
}

.scope-richtext :deep(img) {
  max-width: 100%;
  border-radius: 8px;
  display: block;
}

@media (max-width: 768px) {
  .scope-section {
    padding: 2rem;
    margin: 1rem 0;
  }

  .section-title {
    font-size: 1.5rem;
  }

  .product-scope {
    gap: 16px;
  }

  .scope-card-content {
    padding: 20px;
  }

  .page-title {
    font-size: 2rem;
  }

  .page-subtitle {
    font-size: 1rem;
  }
}

/* 导航菜单样式 - 参考关于我们页面 */
.nav-menu {
  background: #f8f9fa;
  padding: 20px 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.about-nav {
  display: flex;
  justify-content: center;
  gap: 30px;
  flex-wrap: wrap;
}

.nav-item {
  text-decoration: none;
  color: #333;
  font-size: 1.1rem;
  font-weight: 500;
  padding: 10px 20px;
  border-radius: 8px;
  transition: background-color 0.3s ease, color 0.3s ease;
  border: 1px solid #eee;
  cursor: pointer;
}

.nav-item:hover {
  background-color: var(--e-global-color-selected);
  color: white;
  border-color: var(--e-global-color-selected);
}

.nav-item.active {
  background-color: var(--e-global-color-selected);
  color: white;
  border-color: var(--e-global-color-selected);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .about-nav {
    gap: 15px;
  }

  .nav-item {
    font-size: 1rem;
    padding: 8px 16px;
  }
}
</style>
